<template>
  <div class="service-container">
    <div class="service-aside">
      <div class="service-header">
        <el-popover
          :visible="visible"
          placement="right-start"
          popper-style="width:fit-content"
          :teleported="true"
        >
          <!-- TODOLIU 添加服务 -->
          <template #reference>
            <el-button icon="plus" plain link @click="visible = true">添加服务</el-button>
          </template>
          <!-- TODOLIU 添加服务列表 -->

          <template #default>
            <subscription-service-poplist v-model="visible" />
          </template>
        </el-popover>
      </div>
      <!-- TODOLIU 已添加 服务列表 -->
      <div class="service-aside-content">
        <SubscriptionServiceSidebar
          v-model="selectKey"
          :serviceVersionVOs="cloneServiceVersionVOs"
          @handleSidebarSelect="handleSidebarSelect"
          @handleSideBarRemove="handleSidebarRemove"
        />
      </div>
    </div>
    <!-- TODOLIU 服务详情内容 -->

    <div style="flex: 1;" v-loading="formDataLoading">
      <SubscriptionServiceMain ref="refSSM"
                               v-if="currentFormServiceVersionVO && currentCurrentServiceVersionVOs"
                               :currentFormServiceVersionVO="currentFormServiceVersionVO"
                               :currentCurrentServiceVersionVOs="currentCurrentServiceVersionVOs"
                               @updateCFSVVO="updateCFSVVO"
      >
      </SubscriptionServiceMain>
    </div>
  </div>
</template>

<!--服务注册-->
<script setup lang="ts">

import { onClickOutside } from '@vueuse/core'
import SubscriptionServicePoplist from './components/list/popup-list.vue'
import SubscriptionServiceSidebar from './components/sidebar/subscription-service-sidebar.vue'
import SubscriptionServiceMain from './components/content/subscription-service-main.vue'
import { ElMessageBox } from 'element-plus'
import { FormConfig } from '@/types/form'
import { ServiceVersionVOType } from '@coolphk/shared-types/low-code'
import { cloneDeep } from 'lodash-es'

import {
  useLatestServiceVersionVOs,
} from '@/components/form-designer/setting-panel/data-source-setting/subscription-service/composable/use-service'
import { PROVIDE_KEY, SERVICE_OPERATION } from '@/utils/constants'
import {
  useJsonSchemaToTree,
} from '@/components/form-designer/setting-panel/data-source-setting/subscription-service/components/content/composables/useJsonSchemaToTree'
import eventBus from '@/utils/event-bus'
import {RootSchemaType} from '@/components/form-designer/setting-panel/data-source-setting/subscription-service/components/content/composables/useJsonSchemaToTree'

defineOptions({
  name: 'subscription-service',
})

const props = defineProps<{
  formConfig: FormConfig
}>()

//显示事物、服务弹窗
const visible = ref(false)
const refPop = ref(null)
const refSSM = ref(null)

const formDataLoading = ref(false)

//左侧列表数据,当前表单的服务列表 TODOLIU 这里仅是赋值，此弹窗关闭后数据暴露，通过refs获取此服务数据
const cloneServiceVersionVOs = ref<ServiceVersionVOType[]>([])
//当前选中的serviceVersionVO
const currentFormServiceVersionVO = ref<ServiceVersionVOType>(null)
//当前最新的服务版本
const currentCurrentServiceVersionVOs = ref<ServiceVersionVOType>(null)
const currentServiceVersionVOs = useLatestServiceVersionVOs()
//左侧列表选中key
const selectKey = ref(null)

// TODOLIU 提供服务列表 配置文件提供的已经存在的服务列表 提供者
provide(PROVIDE_KEY.CLONE_SERVICE_VERSION_VOS, cloneServiceVersionVOs)

onMounted(() => {
  cloneServiceVersionVOs.value = cloneDeep(props.formConfig.serviceVersionVOs)
  console.log('subscription-service',props.formConfig.serviceVersionVOs)
  onClickOutside(refPop.value, () => {
    visible.value = false
  })
})


/**
 * 处理侧边栏选择事件的函数
 * 当用户在侧边栏选择某一项时，该函数会被调用，以更新界面显示的详细信息
 * @param {number} id - 被选中项的ID，用于识别和获取相应的数据
 */
const handleSidebarSelect = (id: string) => {
  console.log('handleSidebarSelect')
  // 更新当前选中项的ID
  selectKey.value = id
  // 获取当前选中服务的表单服务
  currentFormServiceVersionVO.value = cloneServiceVersionVOs.value.find(item => item.id == id)

  // console.log('currentFormServiceVersionVO', currentFormServiceVersionVO.value)
  // 获取当前选中服务的发布服务
  currentCurrentServiceVersionVOs.value = currentServiceVersionVOs.find(item => item.service.id == currentFormServiceVersionVO.value.service.id)
  //将模型树初始化，如果原表单的模型树为空，代表是从poplist调用，则需要初始化。否则不需要初始化。
  useJsonSchemaToTree(currentFormServiceVersionVO.value, 'inputModel')
  useJsonSchemaToTree(currentCurrentServiceVersionVOs.value, 'inputModel')
  useJsonSchemaToTree(currentFormServiceVersionVO.value, 'outputModel')
  useJsonSchemaToTree(currentCurrentServiceVersionVOs.value, 'outputModel')
}

const handleSidebarRemove = (id: string) => {
  const serviceIndex = cloneServiceVersionVOs.value.findIndex(item => item.id === id)
  ElMessageBox.confirm(`是否要删除服务 [${cloneServiceVersionVOs.value[serviceIndex].service.name}]`).then(() => {
    cloneServiceVersionVOs.value.splice(serviceIndex, 1)
    selectKey.value = null
    currentFormServiceVersionVO.value = null
  })
}
const updateCFSVVO = (newCFSVVO: ServiceVersionVOType) => {
  console.log('updateCFSVVO', newCFSVVO)
  const index = cloneServiceVersionVOs.value.findIndex((item) => item.id == currentFormServiceVersionVO.value.id)
  if (index != -1) {
    eventBus.$emit(SERVICE_OPERATION.UPDATE, {
      oldId: currentFormServiceVersionVO.value.id,
      newId: newCFSVVO.id,
    })
    currentFormServiceVersionVO.value = newCFSVVO

    cloneServiceVersionVOs.value.splice(index, 1, newCFSVVO)
  }
}

// TODOLIU 此弹窗关闭后数据暴露，通过refs获取此服务数据
defineExpose({
  // bindModelTreeToService,
  currentCurrentServiceVersionVOs,
  cloneServiceVersionVOs,
  handleSidebarSelect,
  handleSidebarRemove,
})
</script>

<style scoped lang="scss">
.service-container {
  height: 760px;
  border: 1px solid #eee;
  display: flex;

  .service-aside {
    width: 300px;
    border-right: 1px solid #eee;
  }

  .service-header {
    background: var(--ep-color-info-light-9);
    height: 40px;
    display: flex;
    justify-content: space-between;
    align-items: center
  }
}

:deep(.ep-cascader-menu) {
  width: 100%;
}

:deep(.ep-cascader-node__prefix) {
  position: absolute
}
</style>
